package cn.xspace.wnx.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.actionsheet.ActionSheet;
import com.cn.wt.wtutils.AppManager;
import com.squareup.picasso.Picasso;
import com.xspace.android.imcommon.entity.ChatMsg;
import com.xspace.android.imcommon.fileupload.IuploadListener;
import com.xspace.android.imcommon.fileupload.UploadMg;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.MediaBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.view.RoundAngleImageView;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.xspace.app.view.TitleBar;
import cn.xspace.library.base.MyBaseActivity;
import cn.xspace.library.ui.activity.LoginAct;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.BuildCache;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpUtils;
import cn.xspace.library.util.Tools;
import cn.xspace.wnx.R;
import cn.xspace.wnx.entity.UserInfoBeanNew;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UserCenterActivity extends MyBaseActivity {

    private static final String TAG = UserCenterActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private RoundAngleImageView mIvUserLogo;
    private RelativeLayout mRelativeUserLogo;
    private TextView mTvUserName;
    private RelativeLayout mLayoutUsername;
    private TextView mTvUserAccount;
    private Button mBtLogout;
    private String userId;

    public static int REQUEST_CODE_CAMERA = 1000;
    public static int REQUEST_CODE_GALLERY = 1001;

    private GalleryFinal.OnHanlderResultCallback mOnHandlerResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int requestCode, List<PhotoInfo> resultList) {
            if (resultList != null) {
                PhotoInfo photoInfo = resultList.get(0);
                dealPic(photoInfo);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
//            ToastU.showSingleS(errorMsg);
        }
    };
    private UserInfoBeanNew userInfoBeanNew;

    private void dealPic(PhotoInfo photoInfo) {
        MediaBean mediaBean = new MediaBean();
        mediaBean.insert_time = String.valueOf(System.currentTimeMillis());
        mediaBean.file_name = getPhotoName(photoInfo.getPhotoPath());
        mediaBean.file_type = "0";
        mediaBean.file_state = "0";
        mediaBean.path_type = "0";
        mediaBean.content = photoInfo.getPhotoPath();
        mediaBean.pic_shoot_time = System.currentTimeMillis() + "";
        updatePic(mediaBean);
    }

    public String getPhotoName(String photoPath) {
        return photoPath.substring(photoPath.lastIndexOf(File.separator) + 1);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_user_center);
        mTitleBar = (TitleBar) findViewById(R.id.user_center_title);
        mTitleBar.setLeftLayoutVisibility(View.GONE);
        mIvUserLogo = (RoundAngleImageView) findViewById(R.id.iv_user_logo);
        mRelativeUserLogo = (RelativeLayout) findViewById(R.id.relative_user_logo);
        mTvUserName = (TextView) findViewById(R.id.tv_user_name);
        mLayoutUsername = (RelativeLayout) findViewById(R.id.layout_username);
        mTvUserAccount = (TextView) findViewById(R.id.tv_user_account);
        mBtLogout = (Button) findViewById(R.id.bt_logout);
    }

    @Override
    protected void initData() {
        super.initData();
        userId = MyInfoUtil.getMyUserid(mContext);
        AppUtils.createDir(AppConstant.IMAGE_HEAD);
        requestNetData();
    }

    @Override
    protected void initListener() {
        mRelativeUserLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showPhotoDialog();
            }
        });
        mBtLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExitDialog();
            }
        });
    }

    private void requestNetData() {
        showWaitDialog();
        LogUtil.e("UserInfoAct     =======     开始请求数据 " + userId);
        final Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", userId);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.QUERY_USER_INFO, requestMap);
                if (OkHttpUtils.isSuccess(bean)) {
                    UserInfoBeanNew userInfoBeanNew = JSONUtil.parseJsonToBean(bean.data, UserInfoBeanNew.class);
                    subscriber.onNext(userInfoBeanNew);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                LogUtil.e("UserInfoAct     =======     请求数据失败 " + userId);
                throwable.printStackTrace();
            }

            @Override
            public void onNext(Object result) {
                hideWaitDialog();
                userInfoBeanNew = (UserInfoBeanNew) result;
                LogUtil.e("UserInfoAct     =======     请求数据成功 " + userInfoBeanNew.user_name);
                if (userInfoBeanNew != null) {
                    LogUtil.e("UserInfoAct     =======     请求图片地址为 " + userInfoBeanNew.user_logo);
                    Picasso.with(mContext).load(userInfoBeanNew.user_logo).into(mIvUserLogo);
                    mTvUserName.setText(userInfoBeanNew.user_name);
                    mTvUserAccount.setText(userInfoBeanNew.user_mobile);
                }
            }
        });
    }

    private void showPhotoDialog() {
        final FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setCropSquare(true)
                .setForceCrop(true)
                .setEnablePreview(true)
                .build();
        ActionSheet.createBuilder(mContext, getSupportFragmentManager())
                .setCancelButtonTitle(R.string.cancel)
                .setOtherButtonTitles(getString(R.string.userinfoact_choose_a_pic), getString(R.string
                        .userinfoact_take_a_pic))
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, functionConfig,
                                        mOnHandlerResultCallback);
                                break;
                            case 1:
                                GalleryFinal.openCamera(REQUEST_CODE_CAMERA, functionConfig,
                                        mOnHandlerResultCallback);
                                break;
                        }
                    }
                }).show();
    }

    /**
     * 弹出退出对话框
     */
    private void showExitDialog() {
        new ConfirmDialog.Builder(mContext).setTitleMsg(getString(R.string.userinfoact_switch_btn_exitapp_txt))
                .setContentMsg(getString(R.string.msgexit))
                .setLeftText(getString(R.string.cancel))
                .setRightText(getString(R.string.button_ok))
                .setMaxLine(2)
                .setRightListener(new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        Tools.exitApp(mContext);
                        BldNavigation.HxXmppLoginout(mContext);
                        AppManager.getAppManager().finishAllActivity();
                        Intent in = new Intent(mContext, LoginAct.class);
                        startActivity(in);
                    }
                })
                .setListener().show();
    }

    protected ArrayList<ChatMsg> uploadList = new ArrayList<>();

    private void updatePic(MediaBean mediaBean) {
        if ("0".equals(mediaBean.file_state)) {
            ChatMsg info = new ChatMsg();
            info.mFileType = mediaBean.file_type;
            info.fileType = mediaBean.content_type;//后缀名
            info.mSendTime = DateUtils.getNowDateTime();
            info.msgId = System.currentTimeMillis();
            info.fromUser = MyInfoUtil.getMyUserid(mContext);
            info.mUUID = MyInfoUtil.getMyUserid(mContext);
            info.platForm = "worklog";
            info.fileName = mediaBean.file_name;
            info.imgPath = mediaBean.content;
            info.picShootTime = mediaBean.pic_shoot_time;

            if (TextUtils.isEmpty(info.fileType) && !TextUtils.isEmpty(info.fileName)) {
                info.fileType = info.fileName.substring(info.fileName.indexOf(".") + 1, info.fileName
                        .length());
            }
            info.uploadUrl = Constants.upLoadFileCommon;
            uploadList.add(info);
            UploadMg.getInstance().uploadFile(uploadList, iuploadListener);
        }
    }

    IuploadListener iuploadListener = new IuploadListener() {
        @Override
        public void onUploadBefore(ChatMsg uploads) {

        }

        @Override
        public void onUploading(int position, long uploaded, long total, float progress, float speed, ChatMsg
                uploads, int current) {
            showWaitDialog("正在上传头像");
        }

        @Override
        public void onUploadError(int position, long uploaded, float progress, ChatMsg uploads, int current) {
//            isHaveFailed = true;
        }

        @Override
        public void onUploadAllFinished(int position, ChatMsg uploads, boolean checkFlag) {
//            uploadFileFinish(uploads);
            hideWaitDialog();
            String url = uploads.mContent;
            LogUtil.e("UserInfoAct    ====       返回图片地址  " + url);
            uploadData("user_logo", url);
//            Picasso.with(mContext).load(url).into(userIcon);
//            Map<String, Object> map = new HashMap<>();
//            map.put(EventBusConstant.TYPE, EventBusConstant.LOGO_UPLOAD_FINISHED);
//            map.put(EventBusConstant.ACTION_KEY, url);
//            EventBus.getDefault().post(map);
//            //保存用户头像信息
//            BuildCache.getAppConfigBean(mContext).userInfoBean.logo = url;
//            PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_LOGO, url);
        }

        @Override
        public void onCancelUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onPauseUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onResumeUpload(int position, ChatMsg uploads, int current) {

        }
    };

    private void uploadData(final String parame, final String data) {
        final Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        map.put(parame, data);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.UPDATE_USER_INFO, map);
                if (OkHttpUtils.isSuccess(bean)) {
                    LogUtil.e("UserInfoAct     =======     返回结果成功");
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                LogUtil.e("UserInfoAct     =======     失败");
            }

            @Override
            public void onNext(Object result) {
                if (result != null) {
                    LogUtil.e("UserInfoAct     =======     返回结果 " + ((BaseReturnBean) result).code);
                    if (parame.equals("user_logo")) {
                        //保存用户头像信息
                        BuildCache.getAppConfigBean(mContext).userInfoBean.user_logo = data;
                        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_LOGO, data);
                        Picasso.with(mContext).load(data).into(mIvUserLogo);
//                        Map<String, Object> map = new HashMap<>();
//                        map.put(EventBusConstant.TYPE, EventBusConstant.LOGO_UPLOAD_FINISHED);
//                        map.put(EventBusConstant.ACTION_KEY, data);
//                        EventBus.getDefault().post(map);
                    }
                }
            }
        });

    }
}
